package com.ccrfid.rmc6.service.device;

import com.ccrfid.rmc6.appconfig.exception.pojo.AppException;
import com.ccrfid.rmc6.appconfig.exception.pojo.CustomErrors;
import com.ccrfid.rmc6.entity.device.AlerterEntity;
import com.ccrfid.rmc6.lbservice3.mq.AlarmLinkageDto;
import com.ccrfid.rmc6.repository.device.AlerterRepository;
import com.ccrfid.rmc6.repository.search.SearchCriteria;
import com.ccrfid.rmc6.resource.device.pojo.FloorPos;
import com.ccrfid.rmc6.service.amq.MqMsgProducer;
import com.ccrfid.rmc6.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import javax.ws.rs.core.Response;
import java.util.List;

@Service
@Transactional
public class AlerterServiceImpl implements AlerterService {
    private static final Logger logger = LoggerFactory.getLogger(AlerterServiceImpl.class);
    @Autowired
    private AlerterRepository alerterRepository;

    @Autowired
    private MqMsgProducer mqMsgProducer;

    @Override
    public Page<AlerterEntity> getAlerterInfoPage(SearchCriteria criteria, Pageable pageable) {
        Page<AlerterEntity> page = alerterRepository.search(criteria, pageable);
        return page;
    }

    @Override
    public List<AlerterEntity> getAlerterList(SearchCriteria criteria, Sort sort) {
        return alerterRepository.search(criteria, sort);
    }

    @Override
    public AlerterEntity getAlerterById(Long alerterId) {
        return alerterRepository.getById(alerterId);
    }

    @Override
    public AlerterEntity createAlerter(AlerterEntity entity) throws AppException {
        if (alerterRepository.existsByIp(entity.getIp())) {
            throw new AppException(Response.Status.CONFLICT.getStatusCode(),
                    CustomErrors.ip_conflict.getCode(), CustomErrors.ip_conflict.getReason(), "");
        }
        return alerterRepository.save(entity);
    }

    @Override
    public AlerterEntity updateAlerter(Long alerterId, AlerterEntity entity) throws AppException {
        checkUpdateParam(alerterId, entity);
        return alerterRepository.save(entity);
    }

    private void checkUpdateParam(Long alerterId, AlerterEntity entity) throws AppException {
        if (!alerterId.equals(entity.getId())) {
            throw new AppException(Response.Status.BAD_REQUEST.getStatusCode(),
                    CustomErrors.different_args.getCode(), CustomErrors.different_args.getReason(), "");
        }
        if (!alerterRepository.existsById(alerterId)) {
            throw new AppException(Response.Status.NOT_FOUND.getStatusCode(),
                    CustomErrors.resource_not_found.getCode(), CustomErrors.resource_not_found.getReason(), "");
        }
        if (alerterRepository.existsByIpAndIdNot(entity.getIp(), alerterId)) {
            throw new AppException(Response.Status.CONFLICT.getStatusCode(),
                    CustomErrors.ip_conflict.getCode(), CustomErrors.ip_conflict.getReason(), "");
        }
    }

    @Override
    public AlerterEntity updatePosition(Long alerterId, FloorPos floorPos) throws AppException {
        if (!alerterRepository.existsById(alerterId)) {
            throw new AppException(Response.Status.NOT_FOUND.getStatusCode(),
                    CustomErrors.resource_not_found.getCode(), CustomErrors.resource_not_found.getReason(), "");
        }
        AlerterEntity entity = alerterRepository.getById(alerterId);
        if (entity != null) {
            entity.setFloorNumber(floorPos.getFloorNumber());
            entity.setPos(floorPos.getPos());
            alerterRepository.save(entity);
        }
        return entity;
    }

    @Override
    public Boolean deletePosition(Long alerterId) throws AppException {
        if (!alerterRepository.existsById(alerterId)) {
            throw new AppException(Response.Status.NOT_FOUND.getStatusCode(),
                    CustomErrors.resource_not_found.getCode(), CustomErrors.resource_not_found.getReason(), "");
        }
        AlerterEntity entity = alerterRepository.getById(alerterId);
        if (entity != null) {
            entity.setFloorNumber(null);
            entity.setPos(null);
            alerterRepository.save(entity);
        }
        return true;
    }

    @Override
    public int deleteAlertersInfo(List<Long> idList) {
        int count = 0;
        for (Long id : idList) {
            if (alerterRepository.existsById(id)) {
                count++;
            }
        }
        if (count > 0) {
            //删除报警器信息
            alerterRepository.deleteByIdIn(idList);
        }
        return count;
    }

    @Override
    public void switchControl(Long id, Integer status) {
        AlerterEntity alerterEntity = alerterRepository.getById(id);
        if(alerterEntity != null && status != null){
            AlarmLinkageDto alarmLinkageDto = new AlarmLinkageDto();
            alarmLinkageDto.setIp(alerterEntity.getIp());
            alarmLinkageDto.setPort(alerterEntity.getPort());
            alarmLinkageDto.setStatus(status);//1开启，0关闭
            String msg = JsonUtil.INSTANCE.writeValueAsString(alarmLinkageDto);
            mqMsgProducer.send2Topic("personnel_alarm_linkage", msg);
        }
    }

}
